package com.fizzkai.p2p.website.controller;

import com.fizzkai.p2p.core.domain.LoginInfo;
import com.fizzkai.p2p.core.exception.DisplayableException;
import com.fizzkai.p2p.core.service.ILoginInfoService;
import com.fizzkai.p2p.core.service.IVerifyCodeService;
import com.fizzkai.p2p.core.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;

@Controller
public class LoginInfoController {

    @Autowired
    private ILoginInfoService loginInfoService;
    @Autowired
    private IVerifyCodeService verifyCodeService;


    /**
     * 注册用户
     *
     * @param username
     * @param password
     * @param verifycode
     * @param confirmPwd
     * @return
     */
    @RequestMapping("/userRegister")
    @ResponseBody
    public Object useRegister(String username, String password, String verifycode, String confirmPwd) {
        loginInfoService.register(username, password, verifycode, confirmPwd);
        return new AjaxResult("注册成功");
    }

    /**
     * 验证 用户是否存在
     *
     * @param username
     * @return true 不存在, false 存在
     */
    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String username) {

        return loginInfoService.checkPhone(username);
    }

    /**
     * 通过 手机 发送验证码
     *
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phoneNumber) {
        // 验证 手机 是否存在
        if (!loginInfoService.checkPhone(phoneNumber)) {
            throw new DisplayableException("该手机已经 注册!");
        }
        verifyCodeService.sendVerifyCodeCode(phoneNumber);
        return new AjaxResult("短信发送成功，请查看手机！");
    }

    /**
     * 聊天
     *
     * @param msg
     * @return
     * @throws Exception
     */
    @RequestMapping("/wechat")
    @ResponseBody
    public Object wechat(String msg) throws Exception {
        return verifyCodeService.sendRealMsg(msg);
    }

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(String username, String password) {
        LoginInfo user = loginInfoService.login(username, password, LoginInfo.USERTYPE_USER);
        if (user == null) {
            throw new DisplayableException("用户密码有误！");
        }
        return new AjaxResult("登录成功");
    }


    @RequestMapping("/test")
    @ResponseBody
    public Object test() throws SQLException {

        System.out.println(loginInfoService);
        return "test";
    }
}
